package com.example.demo.service;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.auth.AuthenticationKit;
import com.example.demo.auth.ClientToken;
import com.example.demo.auth.TokenResult;
import com.example.demo.dao.TokenDao;
import com.example.demo.entity.TToken;

@Service
public class TokenService {
	static Logger log = LoggerFactory.getLogger(TokenService.class);

	@Autowired
	TokenDao tokenDao;

	public long modifyToken(String appid, String tokenStr) {
		TToken token = tokenDao.findAllByAppid(appid);
		token.setExpire(getExprie2h());
		token.setToken(tokenStr);

		try {
			tokenDao.save(token);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return token.getExpire();
	}

	/**
	 * 获取当前2小时后的时间 精确到秒
	 * 
	 * @return
	 */
	public long getExprie2h() {
		// 保存到数据库
		long cur = System.currentTimeMillis() / 1000;
		long expires_in = cur + 7200;
		return expires_in;
	}

	/**
	 * 生成token
	 * 
	 * @param clientToken
	 *            接收的参数实体
	 * @param request
	 * @return
	 */
	public String generateToken(ClientToken clientToken, HttpServletRequest request) {

		try {
			// 1.验证appid
			String app_secret = querySecretByAppid(clientToken.getAppid());
			if (app_secret == null) {
				return TokenResult.gettokenResult().getInvalidAppidMsg();
			}
			// 2.验证timestamp
			if (!clientToken.checkTimestamp()) {
				return TokenResult.gettokenResult().getInvalidtimestampMsg();
			}
			// 3.验证nonce
			if (!clientToken.checkNonce()) {
				return TokenResult.gettokenResult().getInvalidnonceMsg();
			}
			// 1.鉴权
			String signUrl = AuthenticationKit.getSignUrl(request, "sign");
			log.info("收到的签名signUrl:" + signUrl);
			String signUrlEncode = AuthenticationKit.signUrlEncode(signUrl, app_secret);
			log.info(String.format("(%1$s)签名对比数据！", "系统签名：" + signUrlEncode + "，客户请求签名数据：" + clientToken.getSign()));
			// 签名无效
			if (!clientToken.checkSign(signUrlEncode)) {
				log.error(String.format("(%1$s)签名对比数据不匹配！",
						"系统签名：" + signUrlEncode + "，客户请求签名数据：" + clientToken.getSign()));
				return TokenResult.gettokenResult().getInvalidSignMsg();
			}
			// 生成token
			String access_token = AuthenticationKit.getToken(clientToken.getAppid());
			// 保存到对应数据库
			long expires_in = modifyToken(clientToken.getAppid(), access_token);
			return TokenResult.gettokenResult().getResultMsg(access_token, expires_in);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return TokenResult.gettokenResult().getErrMsg();
	}

	private String querySecretByAppid(String appid) {
		TToken token = tokenDao.findAllByAppid(appid);
		if (token == null) {
			return null;
		}
		return token.getAppSecret();
	}

	public TToken findByAppId(String appid) {
		TToken token = tokenDao.findAllByAppid(appid);
		if (token == null) {
			return null;
		}
		return token;
	}
}
